﻿using System;
using System.Collections;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic.ClassFactory;
using Common;
using LitJson;
using ValidateCommon;
using DataAccess;
using System.Text.RegularExpressions;
using System.Text;
using System.Data;

namespace RichECMS.ServerPages.User
{
    public partial class UserManage : Util.BasePage.BasePage
    {
        public string strPermissionsText = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (State.LoginUser.ManagerCompetence > (int)Utility.ManagerCompetence.Admin)
            {
                Response.Write("您没有权限查看改页面");
                Response.End();
            }

            if (!Page.IsPostBack)
            {
                if (State.IsManager)
                {
                    TreeBing();
                    if (Request["URID"] != null)
                    {
                        if (ParamAuth.IsNumber(Request["URID"].ToString()))
                        {
                            ShowUserData(Convert.ToInt32(Request["URID"]));
                        }
                    }
                }
                else
                {
                    Response.Write("您没有权限查看该页面");
                    Response.End();
                }
            }
        }

        /// <summary>
        /// 构建管理员树
        /// </summary>
        private void TreeBing()
        {
            //加载站点树说明
            TreeNode objNode = new TreeNode();
            objNode.Value = "0";
            objNode.Text = "管理员列表";
            objNode.Target = "I3";
            objNode.ImageUrl = "../../sysCommon/sysImages/sectionroot.png";
            UserWebTree.Nodes.Add(objNode);

            using (UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory())
            {
                BusinessLogic.BusinessRules.UserWebRelation objUserWebRelation = objUserWebRelationFactory.NewInstance();
                if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.SysAdmin)
                {
                    objUserWebRelation = objUserWebRelationFactory.CreatorBySql(string.Format("  intWSID={0}  order by dtmDateInTime desc", State.intWSID));
                }
                else if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.Designer)
                {
                    objUserWebRelation = objUserWebRelationFactory.CreatorBySql(string.Format("  intManager>2 and  intWSID={0}  order by dtmDateInTime desc ", State.intWSID));
                }
                else if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.Admin)
                {
                    objUserWebRelation = objUserWebRelationFactory.CreatorBySql(string.Format("   intManager>3 and  intWSID={0}  order by dtmDateInTime desc", State.intWSID));
                }


                if (objUserWebRelation != null)
                {
                    foreach (Model.Data.UserWebRelationData.UserWebRelationRow objRow in objUserWebRelation.Data.UserWebRelation.Rows)
                    {
                        TreeNode rootNode = new TreeNode();
                        rootNode.Text = objRow.chvLoginName;
                        rootNode.Value = objRow.intUserWebRelationID.ToString();
                        rootNode.NavigateUrl = "UserManage.aspx?URID=" + objRow.intUserWebRelationID;
                        rootNode.ImageUrl = "../../sysCommon/sysImages/treenode.png";
                        objNode.ChildNodes.Add(rootNode);
                    }
                }
            }
        }

        private void ShowUserData(int intUserWebID)
        {
            using (UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory())
            {
                BusinessLogic.BusinessRules.UserWebRelation objUserWebRelation = objUserWebRelationFactory.CreatorBySql(string.Format(" intUserWebRelationID ={0} and intWSID={1}  ", intUserWebID, State.intWSID));
                if (objUserWebRelation != null)
                {
                    txtUserLoginID.Text = objUserWebRelation.DataItem.chvLoginName;
                    this.txtUserLoginID.ReadOnly = true;
                    this.txtUserPSD.ReadOnly = true;
                    this.txtUserRePSD.ReadOnly = true;
                    HIddenUserID.Value = objUserWebRelation.DataItem.intUserWebRelationID.ToString();

                    DataTable tblTmp = objUserWebRelation.Data.Tables[0];
                    DataRow row = tblTmp.Rows[0];
                    if (objUserWebRelation.DataItem.intManager > (int)Utility.ManagerCompetence.SysAdmin)
                    {
                        sectionCurrentSelect.Value = row["chvPermissions"] != DBNull.Value ? objUserWebRelation.DataItem.chvPermissions : "";
                        this.selectSectionvalue.Value = row["chvPermissionsText"] != DBNull.Value ? objUserWebRelation.DataItem.chvPermissionsText : "";
                    }
                    else
                    {
                        sectionCurrentSelect.Value = "";
                        this.selectSectionvalue.Value = "";
                    }
                    this.txtUserName.Text = row["chvUserName"] != DBNull.Value ? objUserWebRelation.DataItem.chvUserName : "";
                    strPermissionsText = this.selectSectionvalue.Value;

                    //控制权限面板
                    if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.SysAdmin)
                    {
                        RbtnDesigner.Visible = true;
                        RbtnAdmin.Visible = true;
                        UserCanIssue.Visible = true;
                        UserCanIssueAndClients.Visible = true;
                        RbtnUser.Visible = true;
                        ImageButtonUpdate.Visible = true;
                    }
                    else if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.Designer)
                    {
                        RbtnDesigner.Visible = false;
                        RbtnAdmin.Visible = true;
                        UserCanIssue.Visible = true;
                        UserCanIssueAndClients.Visible = true;
                        RbtnUser.Visible = true;
                        ImageButtonUpdate.Visible = true;
                    }
                    else if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.Admin)
                    {
                        RbtnDesigner.Visible = false;
                        RbtnAdmin.Visible = false;
                        UserCanIssue.Visible = true;
                        UserCanIssueAndClients.Visible = true;
                        RbtnUser.Visible = true;
                        ImageButtonUpdate.Visible = true;
                    }
                    else
                    {
                        ImageButtonUpdate.Visible = false;
                    }

                    ImageButtonAdd.Visible = false;

                    //是否启用
                    if (objUserWebRelation.DataItem.intState == (int)Utility.UserState.Enabled)
                    {
                        CKboxEnabled.Checked = true;
                    }
                    else
                    {
                        CKboxEnabled.Checked = false;
                    }

                    //读取权限
                    if (objUserWebRelation.DataItem.intManager == (int)Utility.ManagerCompetence.SysAdmin)
                    {
                        UserCanIssue.Checked = false;
                        UserCanIssueAndClients.Checked = false;
                        RbtnUser.Checked = false;
                        RbtnDesigner.Checked = false;
                        RbtnAdmin.Checked = false;
                        ImageButtonUpdate.Visible = false;
                    }
                    else if (objUserWebRelation.DataItem.intManager == (int)Utility.ManagerCompetence.Designer)
                    {
                        UserCanIssue.Checked = false;
                        UserCanIssueAndClients.Checked = false;
                        RbtnUser.Checked = false;
                        RbtnDesigner.Checked = true;
                        RbtnAdmin.Checked = false;
                    }
                    else if (objUserWebRelation.DataItem.intManager == (int)Utility.ManagerCompetence.Admin)
                    {
                        UserCanIssue.Checked = false;
                        UserCanIssueAndClients.Checked = false;
                        RbtnUser.Checked = false;
                        RbtnDesigner.Checked = false;
                        RbtnAdmin.Checked = true;
                    }
                    else if (objUserWebRelation.DataItem.intManager == (int)Utility.ManagerCompetence.UserCanIssueAndClients)
                    {
                        UserCanIssue.Checked = false;
                        UserCanIssueAndClients.Checked = true;
                        RbtnUser.Checked = false;
                        RbtnDesigner.Checked = false;
                        RbtnAdmin.Checked = false;
                    }
                    else if (objUserWebRelation.DataItem.intManager == (int)Utility.ManagerCompetence.UserCanIssue)
                    {
                        UserCanIssue.Checked = true;
                        UserCanIssueAndClients.Checked = false;
                        RbtnUser.Checked = false;
                        RbtnDesigner.Checked = false;
                        RbtnAdmin.Checked = false;
                    }
                    else
                    {
                        UserCanIssue.Checked = false;
                        UserCanIssueAndClients.Checked = false;
                        RbtnUser.Checked = true;
                        RbtnDesigner.Checked = false;
                        RbtnAdmin.Checked = false;
                    }
                }
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private bool ValidateValues()
        {
            bool bolIsValidate = true;
            if (this.txtUserLoginID.Text.Trim().Length == 0)
            {
                Alert("请填写登陆ID");
                bolIsValidate = false;
                return bolIsValidate;
            }
            Regex re = new Regex(@"^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
            if (!re.IsMatch(this.txtUserLoginID.Text.Trim()))
            {
                Alert("您输入的登录ID里含有非法字符，请输入字母，数字 下划线的组合，下划线不能再开头或结尾");
                bolIsValidate = false;
                return bolIsValidate;
            }
            if (this.txtUserName.Text.Trim().Length == 0)
            {
                Alert("请填写用户名");
                bolIsValidate = false;
                return bolIsValidate;
            }
            if (this.txtUserPSD.Text.Replace("'", "") != this.txtUserRePSD.Text)
            {
                Alert("密码不一致");
                bolIsValidate = false;
                return bolIsValidate;
            }
            using (UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory())
            {
                BusinessLogic.BusinessRules.UserWebRelation objUserWebRelation = objUserWebRelationFactory.CreatorBySql(string.Format(" chvLoginName ='{0}' and intWSID={1} ", this.txtUserLoginID.Text.Replace("'", ""), State.intWSID));
                if (objUserWebRelation != null)
                {
                    Alert("此用户名已经具有该站点管理权");
                    bolIsValidate = false;
                    return bolIsValidate;
                }
            }
            return bolIsValidate;
        }


        protected void ImageButtonAdd_Click(object sender, ImageClickEventArgs e)
        {
            if (!ValidateValues())
            {
                return;
            }

            StringBuilder stringBuilderMessage = new StringBuilder();
            using (DBManager objDBManager = new DBManager())
            {
                objDBManager.BeginTransaction();
                try
                {
                    UserManageInfoFactory objUserManageInfoFactory = new UserManageInfoFactory(objDBManager);
                    BusinessLogic.BusinessRules.UserManageInfo objUserManageInfo = objUserManageInfoFactory.CreatorBySql(string.Format(" chvLoginName ='{0}' and intWSID={1} ", this.txtUserLoginID.Text.Replace("'", ""), State.intWSID));
                    if (objUserManageInfo != null)
                    {
                        stringBuilderMessage.Append("此管理账户已经存在，已完成对此账户添加该网站管理权限操作");
                    }
                    else
                    {
                        //管理员表
                        objUserManageInfoFactory = new UserManageInfoFactory();
                        objUserManageInfo = objUserManageInfoFactory.NewInstance();
                        objUserManageInfo.DataItem.chvLoginName = this.txtUserLoginID.Text;
                        objUserManageInfo.DataItem.chvLoginPsw = EncryptUtily.EncryptUtily.LoginEncrypt(this.txtUserPSD.Text.Trim());
                        objUserManageInfo.DataItem.intWSID = State.intWSID;
                        objUserManageInfo.DataItem.dtmInTime = DateTime.Now;
                        objUserManageInfo.Insert();
                        stringBuilderMessage.Append("添加账户成功");
                    }


                    //管理关联表
                    UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory();
                    BusinessLogic.BusinessRules.UserWebRelation objUserWebRelation = objUserWebRelationFactory.NewInstance();
                    objUserWebRelation.DataItem.chvLoginName = objUserManageInfo.DataItem.chvLoginName;
                    objUserWebRelation.DataItem.chvUserName = this.txtUserName.Text;
                    objUserWebRelation.DataItem.intWSID = State.intWSID;
                    objUserWebRelation.DataItem.intState = (int)Utility.UserState.Enabled;

                    if (RbtnAdmin.Checked)
                    {
                        objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.Admin;
                    }
                    else if (RbtnDesigner.Checked)
                    {
                        objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.Designer;
                    }
                    else if (UserCanIssueAndClients.Checked)
                    {
                        objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.UserCanIssueAndClients;
                    }
                    else if (UserCanIssue.Checked)
                    {
                        objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.UserCanIssue;
                    }
                    else if (RbtnUser.Checked)
                    {
                        objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.User;
                    }

                    objUserWebRelation.DataItem.intUserID = objUserManageInfo.DataItem.intUserID;
                    if (objUserWebRelation.DataItem.intManager > (int)Utility.ManagerCompetence.SysAdmin)
                    {
                        objUserWebRelation.DataItem.chvPermissions = sectionCurrentSelect.Value;
                        objUserWebRelation.DataItem.chvPermissionsText = this.selectSectionvalue.Value;
                    }
                    else
                    {
                        objUserWebRelation.DataItem.chvPermissions = "";
                        objUserWebRelation.DataItem.chvPermissionsText = "";
                    }

                    objUserWebRelation.DataItem.dtmDateInTime = DateTime.Now;

                    objUserWebRelation.Insert();
                    //提交

                    objDBManager.Commit();
                    objUserWebRelationFactory.Dispose();
                    objUserManageInfoFactory.Dispose();

                }
                catch (Exception ex)
                {
                    Alert(ex.Message.ToString().Replace("\r\n", " "));
                    objDBManager.Rollback();
                    objDBManager.Dispose();
                    return;
                }
            }
            AlertAndRedirect(stringBuilderMessage.ToString(), "UserManage.aspx", false);
        }

        protected void ImageButtonUpdate_Click(object sender, ImageClickEventArgs e)
        {
            StringBuilder stringBuilderMessage = new StringBuilder();
            using (DBManager objDBManager = new DBManager())
            {
                objDBManager.BeginTransaction();
                try
                {
                    using (UserWebRelationFactory objUserWebRelationFactory = new UserWebRelationFactory(objDBManager))
                    {
                        BusinessLogic.BusinessRules.UserWebRelation objUserWebRelation = objUserWebRelationFactory.CreatorBySql(string.Format(" intUserWebRelationID ={0} and intWSID={1} ", HIddenUserID.Value, State.intWSID));
                        if (objUserWebRelation != null)
                        {
                            if (objUserWebRelation.DataItem.intManager > (int)Utility.ManagerCompetence.SysAdmin)
                            {
                                objUserWebRelation.DataItem.chvPermissions = sectionCurrentSelect.Value;
                                objUserWebRelation.DataItem.chvPermissionsText = this.selectSectionvalue.Value;
                            }
                            else
                            {
                                objUserWebRelation.DataItem.chvPermissions = "";
                                objUserWebRelation.DataItem.chvPermissionsText = "";
                            }

                            //角色
                            if (RbtnAdmin.Checked)
                            {
                                objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.Admin;
                            }
                            else if (RbtnDesigner.Checked)
                            {
                                objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.Designer;
                            }
                            else if (UserCanIssueAndClients.Checked)
                            {
                                objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.UserCanIssueAndClients;
                            }
                            else if (RbtnUser.Checked)
                            {
                                objUserWebRelation.DataItem.intManager = (int)Utility.ManagerCompetence.User;
                            }

                            //是否启用
                            objUserWebRelation.DataItem.intState = (CKboxEnabled.Checked) == true ? (int)Utility.UserState.Enabled : (int)Utility.UserState.Disabled;
                            objUserWebRelation.Update();
                            stringBuilderMessage.Append("修改账户成功");
                        }
                        objDBManager.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Alert(ex.Message.ToString().Replace("\r\n", " "));
                    objDBManager.Rollback();
                    objDBManager.Dispose();
                    return;
                }
            }
            AlertAndRedirect(stringBuilderMessage.ToString(), "UserManage.aspx", false);
        }

        protected void LinkButtonAddUser_Click(object sender, EventArgs e)
        {
            this.txtUserPSD.Text = "";
            this.txtUserRePSD.Text = "";
            this.txtUserName.Text = "";
            this.txtUserLoginID.Text = "";

            this.txtUserLoginID.ReadOnly = false;
            this.txtUserPSD.ReadOnly = false;
            this.txtUserRePSD.ReadOnly = false;

            //控制权限面板
            if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.SysAdmin)
            {
                RbtnDesigner.Visible = true;
                RbtnAdmin.Visible = true;
                UserCanIssueAndClients.Visible = true;
                RbtnUser.Visible = true;
                ImageButtonAdd.Visible = true;
            }
            else if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.Designer)
            {
                RbtnDesigner.Visible = false;
                RbtnAdmin.Visible = true;
                UserCanIssueAndClients.Visible = true;
                RbtnUser.Visible = true;
                ImageButtonAdd.Visible = true;
            }
            else if (State.LoginUser.ManagerCompetence == (int)Utility.ManagerCompetence.Admin)
            {
                RbtnDesigner.Visible = false;
                RbtnAdmin.Visible = false;
                UserCanIssueAndClients.Visible = true;
                RbtnUser.Visible = true;
                ImageButtonAdd.Visible = true;
            }
            else
            {
                ImageButtonAdd.Visible = false;
            }

            ImageButtonUpdate.Visible = false;
        }
    }
}